package cn.tramy.pinxian.wind.domain.repository

import cn.tramy.pinxian.wind.domain.DomainModelHolder
import cn.tramy.pinxian.wind.domain.model.BaseDomainModel
import org.springframework.data.jpa.repository.support.JpaEntityInformation
import org.springframework.data.jpa.repository.support.SimpleJpaRepository
import org.springframework.data.repository.NoRepositoryBean
import javax.persistence.EntityManager

@NoRepositoryBean
class WindRepositoryImpl<T : Any, ID>(entityInformation: JpaEntityInformation<T, *>?, entityManager: EntityManager?) : SimpleJpaRepository<T, ID>(entityInformation, entityManager) {

    private fun addModelsToHolder(vararg models: Any) {
        models.filter { it is BaseDomainModel }.map { it as BaseDomainModel }.forEach { DomainModelHolder.current().addDomainModel(it) }
    }

    override fun <S : T> saveAndFlush(entity: S): S {
        val s = super.saveAndFlush(entity)
        this.addModelsToHolder(entity)
        return s
    }

    override fun <S : T> save(entity: S): S {
        val s = super.save(entity)
        addModelsToHolder(entity)
        return s
    }

    override fun <S : T> saveAll(entities: MutableIterable<S>): MutableList<S> {

        val result = super.saveAll(entities)
        this.addModelsToHolder(entities)
        return result
    }
}